package jpaperwork.meta.transformer;

import jpaperwork.meta.descriptor.*;
import jpaperwork.utils.ReflectionUtils;

import java.util.List;

/**
 * User: fleipold
 * Date: Jun 30, 2009
 * Time: 10:06:30 PM
 */
public class BeanFormReader implements FormReader {
    public Object readFieldValue(Field field, Object transformee) {
      return get(transformee, field.getName());   
    }

    public List readCollectionValues(Aggregation aggregation, Object transformee) {
        return (List) transformee;
    }               

    public PolymorphicValue determineType(Polymorphism polymorphism, Object transformee) {
        for (DiscriminatedType type : polymorphism.getTypes() ){
            if (transformee.getClass().isAssignableFrom(type.getForm().getDecoration(ClassFormDecoration.class).getClazz())){
                return new PolymorphicValue(type, transformee);
            }

        }
        throw new IllegalArgumentException("Could not find type for bean class "+ transformee.getClass());
    }


    public Object get(Object form, String fieldName) {
        final Class<? extends Object> formClazz = form.getClass();
        try {
            java.lang.reflect.Field field = ReflectionUtils.getDeclaredField(formClazz, fieldName);

            field.setAccessible(true);
            return field.get(form);

        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }
}
             
